//
//  MYUserAccountViewModel.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/23.
//  Copyright © 2016年 lianglong. All rights reserved.
//

import UIKit
import SVProgressHUD

private let userInfoKey = "userInfoKey"


class MYUserAccountViewModel: NSObject {
    
    static let shareUserAccountViewModel: MYUserAccountViewModel = MYUserAccountViewModel()
    
    var userAccount: MYUserAccount?
    
    private override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    
    //计算属性
    var userLogin: Bool {
        //如果用户的token和现在时间比较是降序,表示token没过期
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
            
            return true
        }
        userAccount = nil
        return false
        
    }
    
    //头像的URL
    var userIcon: NSURL? {
        get {
            return NSURL(string: self.userAccount?.avatar_large ?? "")
        }
    }
    
    
    
}


extension MYUserAccountViewModel {
    
    //MARK:通过code获取token
    func loadAccountToken(code: String, finished: (isSuccess: Bool) -> ()) {
        
        MYNetworkingTools.shareTools.loadAccountToken(code) { (responseObject, error) in
            
            //如果有错误, 执行失败闭包
            if error != nil {
                
                finished(isSuccess: false)
                return
            }
            
            self.loadUserInfo(responseObject, finshed: finished)
           // print(responseObject)
        }
        
        
    }
        
    //请求用户信息的方法
    private func loadUserInfo(respone: AnyObject?, finshed: (isSuccess: Bool) -> ()) {
        
        guard let result = respone as? [String : AnyObject] else {
           // SVProgressHUD.showErrorWithStatus("请检查网络")
            return
        }
        
        MYNetworkingTools.shareTools.loadUserInfo(result) { (responseObject, error) in
            
            //有错误时,
            if error != nil {
                finshed(isSuccess: false)
                return
            }
            
            //响应的数据不能转化成字典
            guard var dict = responseObject as? [String : AnyObject] else {
                finshed(isSuccess: false)
                return
            }
            
            //请求成功
            //拼接字典,便于缓存到本地
            for (key, value) in result {
                dict[key] = value
            }
            
            self.saveUserAccount(dict)
            
            finshed(isSuccess: true)
        }
    }
}



extension MYUserAccountViewModel {
    
    //存储用户信息
    func saveUserAccount(dict: [String : AnyObject]) {
        
        let userAccount = MYUserAccount(dict: dict)
        
        //MARK: 为了 解决 从 未登录状态 -> 登陆状态 userAccount 为nil 的bug
        self.userAccount = userAccount
        
        let keys = ["access_token", "expires_date", "expires_in", "uid", "name", "avatar_large"]
        
        //模型数组转成OC字典
        let userInfo = userAccount.dictionaryWithValuesForKeys(keys)
        
        //存储到偏好设置
        let userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(userInfo, forKey: userInfoKey)
        userDefault.synchronize()
        
        
    }
    
    //读取用户信息
    func loadUserAccount() -> MYUserAccount? {
        
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            
            return nil
        }
        
        
        let user = MYUserAccount(dict: dict)
        
        return user
    }
    
    
    
    
}
